<template>
  <div v-loading="busing">
    <div class="img-size-box"
         v-show="sizing">
      <div class="img-size"
           :style="imgStyle"
           ref="imgSize">
      </div>
      <div class="tool-tm">
        <div class="pre-tm needsclick"
             @click="start">重选</div>
        <div class="roll-tm needsclick"
             @click="reset">重置</div>
        <div class="save-tm"
             ref="over">确定</div>
      </div>
      <div v-if="cut === false"
           style="display:none">
        <img :src="src"
             v-if="src"
             @load="finish($event)">
      </div>

      <input type="file"
             class="file"
             accept="image/*"
             @change="handelChange"
             ref="file">
    </div>
  </div>
</template>
<script>
import PhotoClip from '@/_thrid/photoclip'
import lrz from 'lrz'
export default {
  props: {
    action: String,
    token: String,
    cut: {
      type: Boolean,
      default: true
    },
    width: {
      type: Number,
      default: 0
    },
    height: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      sizing: false,
      pc: null,
      progress: 0,
      mime: 'image/jpeg',
      busing: false,
      src: null
    }
  },
  computed: {
    imgStyle () {
      if (this.width > 0 && this.height > 0) {
        return {
          width: `${this.$math.calc(this.width).div(100).mul(window.defaultFontSize).mul(1.2).over()}px`,
          height: `${this.$math.calc(this.height).div(100).mul(window.defaultFontSize).mul(1.2).over()}px`
        }
      }
    }
  },
  methods: {
    base2blob (base64Data) {
      const base64 = base64Data
      const code = window.atob(base64.split(',')[1])
      const aBuffer = new window.ArrayBuffer(code.length)
      const uBuffer = new window.Uint8Array(aBuffer)
      for (let i = 0; i < code.length; i++) {
        uBuffer[i] = code.charCodeAt(i) & 0xff
      }
      let blob = null
      try {
        blob = new Blob([uBuffer], {
          type: this.mime
        })
      } catch (e) {
        window.BlobBuilder = window.BlobBuilder ||
          window.WebKitBlobBuilder ||
          window.MozBlobBuilder ||
          window.MSBlobBuilder
        if (e.name == 'TypeError' && window.BlobBuilder) {
          let bb = new window.BlobBuilder()
          bb.append(uBuffer.buffer)
          blob = bb.getBlob(this.mime)
        } else if (e.name == 'InvalidStateError') {
          blob = new Blob([aBuffer], {
            type: this.mime
          })
        } else {}
      }
      return blob
    },
    done (file) {
      this.$emit('start')
      this.sizing = false
      this.busing = true
      let xhr = new XMLHttpRequest()
      // 上传中
      xhr.upload.onprogress = e => {
        if (e.lengthComputable) {
          let progress = Math.round((e.loaded * 100) / e.total)
          if (this.progress < progress) {
            this.progress = progress
            this.$emit('progress', progress)
          }
        }
      }
      // 上传完成
      xhr.upload.onload = () => {
        this.progress = 100
        this.$emit('progress', 100)
      }
      let url = this.action
      // 避免浏览器缓存http请求
      url += ((/\?/).test(this.action) ? '&' : '?') + (new Date())
        .getTime()
      xhr.open('POST', url, true)
      xhr.setRequestHeader('Mime', this.mime)
      xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
          if (xhr.status == 200 && xhr.responseText != '') {
            const result = JSON.parse(xhr.responseText)
            this.$emit('success', result.key, this.naturalHeight, this.naturalWidth)
            this.$emit('end')
            this.$refs.file.value = null
            this.pc.clear()
            this.busing = false
          } else {
            this.$emit('fail', xhr.response)
            this.$emit('end')
            this.$refs.file.value = null
            this.pc.clear()
            this.busing = false
          }
        }
      }
      let formData = new FormData()
      formData.append('token', this.token)
      formData.append('file', file)
      xhr.send(formData)
    },
    start (width, height) {
      if (this.cut === true) {
        if (this.width > 0 && this.height > 0) {
          this.pc.size(
            this.$math.calc(this.width).div(100).mul(window.defaultFontSize).over(),
            this.$math.calc(this.height).div(100).mul(window.defaultFontSize).over()
          )
        }
        if (width > 0 && height > 0) {
          this.pc.size(
            this.$math.calc(width).div(100).mul(window.defaultFontSize).over(),
            this.$math.calc(height).div(100).mul(window.defaultFontSize).over()
          )
        }
      }
      const event = new MouseEvent('click')
      this.$refs.file.dispatchEvent(event)
    },
    async handelChange () {
      if (this.$refs.file.value) {
        if (this.cut === true) {
          this.sizing = true
        } else {
          const data = await lrz(this.$refs.file.files[0], {
            // width: this.$math.calc(this.width).div(100).mul(window.defaultFontSize).over()
          })
          // this.$refs.file.files.
          this.src = data.base64
        }
      }
    },
    finish (event) {
      this.naturalHeight = event.target.naturalHeight
      this.naturalWidth = event.target.naturalWidth
      this.done(event.target.src)
    },
    reset () {
      this.pc.rotate(0, 800)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.pc = new PhotoClip(this.$refs.imgSize, {
        size: 300,
        // adaptive: '50%',
        outputQuality: 0.6,
        file: this.$refs.file,
        ok: this.$refs.over,
        done: this.done,
        rotateFree: false
      })
    })
  }
}
</script>
<style lang="stylus" scoped>
.tool-tm {
  width: 750px;
  height: 112px;
  background: rgba(0, 0, 0, 0.7);
  position: fixed;
  bottom: 0;
  z-index: 6000;
  display: flex;
  justify-content: space-around;
  align-content: center;
  align-items: center;

  .pre-tm {
    width: 218px;
    height: 70px;
    background: rgba(220, 220, 220, 1);
    border-radius: 100px;
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    font-size: 30px;
    font-family: PingFangSC-Regular;
    color: rgba(51, 51, 51, 1);
  }

  .save-tm {
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    width: 218px;
    height: 70px;
    background: linear-gradient(103.9deg, rgba(243, 45, 102, 1), rgba(255, 144, 173, 1));
    border-radius: 100px;
    font-size: 30px;
    font-family: PingFangSC-Regular;
    color: rgba(255, 255, 255, 1);
  }

  .back-tm {
    margin-left: 0;
  }

  .roll-tm {
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    width: 218px;
    height: 70px;
    background: rgb(250, 187, 80);
    border-radius: 100px;
    font-size: 30px;
    font-family: PingFangSC-Regular;
    color: rgba(255, 255, 255, 1);
  }
}

.img-size-box {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  background: rgba(0, 0, 0, 0.8);
  z-index: 6002;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  flex-wrap: wrap;
  align-content: flex-start;
  padding-top: 200px;

  .img-size {
    height: 750px;
    width: 100vw;
    background: rgba(255, 255, 255, 1);
  }
}

.file {
  opacity: 0;
  position: absolute;
  left: -10rem;
}
</style>
